package cloud.tianai.mate.captcha.resource.impl.provider;

import cloud.tianai.captcha.resource.AbstractResourceProvider;
import cloud.tianai.captcha.resource.common.model.dto.Resource;
import lombok.SneakyThrows;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Author: 天爱有情
 * @date 2024/7/17 10:44
 * @Description 随机马赛克图片，大小可以在 data中设置  比如 600*360
 */
public class RandomMosaicResourceProvider extends AbstractResourceProvider {

    public static final String NAME = "random_mosaic";
    List<Color> colors = Arrays.asList(
            new Color(254, 220, 172),
            new Color(218, 196, 220),
            new Color(252, 249, 207),
            new Color(181, 203, 225),
            new Color(251, 182, 180),
            new Color(227, 209, 184)
    );

    @Override
    @SneakyThrows
    public InputStream doGetResourceInputStream(Resource data) {
        int width = 600;
        int height = 360;
        String str = data.getData();
        if (str != null && str.indexOf("x") > 0) {
            String[] split = str.split("x");
            width = Integer.parseInt(split[0]);
            height = Integer.parseInt(split[1]);
        }
        ThreadLocalRandom random = ThreadLocalRandom.current();
        int mosaicSizeX =  random.nextInt(64, 128); // 马赛克块大小
        int mosaicSizeY = random.nextInt(64, 128); // 马赛克块大小

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        for (int x = 0; x < width; x += mosaicSizeX) {
            for (int y = 0; y < height; y += mosaicSizeY) {
                Color randomColor = getRandomColor();
                g.setColor(randomColor);
                g.fillRect(x, y, mosaicSizeX, mosaicSizeY);
            }
        }
        g.dispose();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", byteArrayOutputStream);

        ByteArrayInputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());

        return inputStream;
    }

    private Color getRandomColor() {

        return colors.get((int) (Math.random() * colors.size()));
    }

    @Override
    public boolean supported(String type) {
        return NAME.equalsIgnoreCase(type);
    }

    @Override
    public String getName() {
        return NAME;
    }
}
